package com.carrot.framework.interceptor;

import com.carrot.framework.holder.SystemContextHolder;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

/**
 * 服务上下文
 */
public class ServerContextInterceptor implements HandlerInterceptor {

    private static final String SYSTEM_TAG_HEADER = "system";

    @Override
    public boolean preHandle(
            HttpServletRequest request, HttpServletResponse response, Object handler){

        if (handler instanceof ResourceHttpRequestHandler) {
            return true;
        }
        String systemTag = request.getHeader(SYSTEM_TAG_HEADER);
        SystemContextHolder.setSystemTag(systemTag);
        return true;
    }

    @Override
    public void afterCompletion(
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex){

        // 上下文属性值清除，防止内存泄漏
        SystemContextHolder.clear();
    }

}
